package com.arlen.photo.photopickup.presenter;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.media.MediaService;
import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadOptions;
import com.arlen.photo.photopickup.util.DensityUtils;
import com.arlen.photo.photopickup.util.FileSizeUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.wbao.dianniu.logical.DnApplication;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.utils.Utils;

/**
 * 上传头像处理类
 * 
 * @author yejianjun
 *
 */
public class HeadPresenter {
	private Activity mActivity;
	private UploadListener mListener;
	/** 网络图片处理service */
//	private MediaService mediaService;
	// namespace
	public static final String namespace = "dianniu";
	private 	String mTaskId;

	public HeadPresenter(Activity activity) {
		this.mActivity = activity;
	}

	public void addUploadListener(UploadListener listener) {
		this.mListener = listener;
	}

	public void uploadImageUrl(final String filePath,final String uploadName) {
		if (TextUtils.isEmpty(filePath))
			return;
		new AsyncTask<String, Void, String>() {
			@Override
			protected String doInBackground(String... params) {
				File file = new File(filePath);
				BitmapFactory.Options options = FileSizeUtil
						.getBitmapOptions(file.getPath());
				int screenMax = Math.max(
						DensityUtils.getWindowWidth(mActivity),
						DensityUtils.getWindowHeight(mActivity));
				int imgMax = Math.max(options.outWidth, options.outHeight);
				System.out.println("dd:" + System.currentTimeMillis());
				int inSimpleSize = 1;
				if (screenMax <= imgMax) {
					inSimpleSize = Math.max(screenMax, imgMax)
							/ Math.min(screenMax, imgMax);
				}
				// 压缩图片并缓存到指定路径
				String compressFile = FileSizeUtil.compressBitmap(mActivity,
						file.getAbsolutePath(), Bitmap.CompressFormat.JPEG,
						options.outWidth / inSimpleSize, options.outHeight
								/ inSimpleSize, false,uploadName);
				final UploadOptions opts = new UploadOptions.Builder()
						.tag(String.valueOf(SystemClock.elapsedRealtime()))
						.dir("images").aliases(uploadName).build();
				if(Build.VERSION.SDK_INT > 23){
					if(null != DnApplication.wantuService){
						mTaskId = DnApplication.wantuService.upload(new File(compressFile), opts, mListener, GlobalContext.cdnToken);
					}else{
						Log.e("HeadPresenter", "无法获取多媒体服务！1");
					}
				}else{
					MediaService mediaService =  AlibabaSDK.getService(MediaService.class);
					if(null != mediaService){
						mTaskId = mediaService.upload(new File(compressFile), namespace, opts, mListener);
					}else{
						Log.e("HeadPresenter", "无法获取多媒体服务！2");
					}
				}
				return compressFile;
			}

			@Override
			protected void onPostExecute(final String fileName) {
				// TODO 用的retrofit 2.0上传图片一次上传一张
			}
		}.execute();
	}
	
	/**
	 * 上传图片 不缓存到本地
	 * 
	 * @param filePath
	 * @param uploadName
	 */
	public void uploadImageNotCompress(final String filePath,final String uploadName) {
		if (TextUtils.isEmpty(filePath))
			return;
		
		new AsyncTask<String, Void, String>() {
			@Override
			protected String doInBackground(String... params) {
				File file = new File(filePath);
				final UploadOptions opts = new UploadOptions.Builder()
						.tag(String.valueOf(SystemClock.elapsedRealtime()))
						.dir("images").aliases(uploadName).build();
				
				if(Build.VERSION.SDK_INT > 23){
					if(null != DnApplication.wantuService){
						DnApplication.wantuService.upload(file, opts, mListener, GlobalContext.cdnToken);
					}else{
						Log.e("HeadPresenter", "无法获取多媒体服务！3");
					}
				}else{
					MediaService mediaService = AlibabaSDK.getService(MediaService.class);
					if(null != mediaService){
						mTaskId = mediaService.upload(file, namespace, opts,mListener);
					}else{
						Log.e("HeadPresenter", "无法获取多媒体服务！4");
					}
				}
				
				return "";
			}

			@Override
			protected void onPostExecute(final String fileName) {
				// TODO 用的retrofit 2.0上传图片一次上传一张
			}
		}.execute();
	}
	
	/**
	 * 
	 * 
	 * @param context	上下文对象	
	 * @param headpic	图片名称--- 不需要加前缀
	 * @param imageview	图片显示的view
	 */
	public void showHeadPic(Context context,final String headpic,final ImageView imageview){
		String desPath = getImageCacheDir(context) + headpic;
		// 查看图片缓存中是否有该图片
		File file = new File(desPath);
		if(file.exists()){	// 内存中存在 直接从缓存中读取
			System.out.println("图片在缓存中..........");
			Glide.with(mActivity)
			.load(file)
			.into(imageview);
		}else{	// 没有加载到内存 先从网络下载，然后再缓存
			System.out.println("图片不在缓存中..........");
			int width = Utils.dip2px(mActivity, 60);
			 SimpleTarget<Bitmap> target = new SimpleTarget<Bitmap>(width,width) {
				 
				@Override
				public void onResourceReady(Bitmap bitmap,GlideAnimation<? super Bitmap> arg1) {
					// TODO Auto-generated method stub
					FileSizeUtil.compressBitmapToCache(mActivity, Bitmap.CompressFormat.JPEG, headpic, bitmap);
					imageview.setImageBitmap(bitmap);
				}
			};
			
			Glide.with(mActivity)
			.load(GlobalContext.cdndownUrl + headpic)
			.asBitmap()
			.centerCrop() 
			.fitCenter()
			.diskCacheStrategy( DiskCacheStrategy.SOURCE )
			.into(target);
		}
		
	}
	
	 /**
     * 获取图片缓存路径
     * @param context
     * @return
     */
    private static String getImageCacheDir(Context context) {
//        String dir = context.getCacheDir() + "Image" + File.separator;
        String dir = Environment.getExternalStorageDirectory() + File.separator + "DnImage" + File.separator;
        File file = new File(dir);
        if (!file.exists()) file.mkdirs();
        return dir;
    }

}
